﻿/**
//  frmComposeMessage.cs
//  Marquee Moment
//  Copyright 2011 Systematix Technocrates. All rights reserved.
**/

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using MarqueeMoment.Entities;
using System.IO;
using System.Drawing.Imaging;
using NLog;
using System.Collections;
using System.Drawing.Drawing2D;
using MJW.Guardian.RuntimeComponents;


namespace MarqueeMoment.Forms
{
    public partial class frmComposeMessage : Form
    {
        #region Form variables
        int selectedBGImageIndex = 0;
        private bool _imageFromCamera = false;
        public bool backgroundSelected = false;
        public bool isFormInitialized = false;
        public static bool formClose = true;
        private static Logger logger = LogManager.GetCurrentClassLogger();
        PictureBox picboxImageCapture;
        PictureBox picboxImageBG;
    //    Label lblMessage = new Label();
        ShadowLabel lblCustomerName;
        ShadowLabel lblCustomerName2;
     //   Label lblShadowText = new Label();
        ShadowLabel lblMessage;

    //    Button imageDefaultButton = new Button();


        #endregion Form variables

        #region Constructor
        public frmComposeMessage()
        {
            logger.Info("On frmComposeMessage()");
            InitializeComponent();
            lbBack.Text = "Back to Main Menu";
            InitializeValues();
        }

        public frmComposeMessage(bool imageFromCamera)
        {
            logger.Info("On frmComposeMessage(bool imageFromCamera) , imageFromCamera:" + imageFromCamera.ToString());
            InitializeComponent();
            _imageFromCamera = imageFromCamera;
            lbBack.Text = "Back to Photo Session";
            InitializeValues();
        }

        #endregion  Constructor

        #region ImageSaveParameters
        [System.Runtime.InteropServices.DllImportAttribute("gdi32.dll")]

        private static extern bool BitBlt

        (

        IntPtr hdcDest, // handle to destination DC

        int nXDest, // x-coord of destination upper-left corner

        int nYDest, // y-coord of destination upper-left corner

        int nWidth, // width of destination rectangle

        int nHeight, // height of destination rectangle

        IntPtr hdcSrc, // handle to source DC

        int nXSrc, // x-coordinate of source upper-left corner

        int nYSrc, // y-coordinate of source upper-left corner

        System.Int32 dwRop // raster operation code

        );
        #endregion ImageSaveParameters

        #region ScrollBarAdd
        [DllImport("user32.dll")]

        static public extern bool ShowScrollBar(System.IntPtr hWnd, int wBar, bool bShow);

        private const uint SB_HORZ = 0;

        private const uint SB_VERT = 1;

        private const uint ESB_DISABLE_BOTH = 0x3;

        private const uint ESB_ENABLE_BOTH = 0x0;

        #endregion ScrollBarAdd

        #region For User Define Method
        /// <summary>
        /// To Show Time on Time Box
        /// </summary>
        private void ShowTime()
        {
            String currentTime = String.Empty;
            var timeZone = TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time");
            currentTime = TimeZoneInfo.ConvertTime(DateTime.Now, timeZone).ToLongTimeString();
            lblPM.Text = currentTime.Substring(currentTime.Length - 2);
            currentTime = currentTime.Substring(0, currentTime.Length - 3);

            lblT8.Text = currentTime.Substring(currentTime.Length - 1);
            lblT7.Text = currentTime.Substring(currentTime.Length - 2, 1);
            lblT6.Text = currentTime.Substring(currentTime.Length - 3, 1);
            lblT5.Text = currentTime.Substring(currentTime.Length - 4, 1);
            lblT4.Text = currentTime.Substring(currentTime.Length - 5, 1);
            lblT3.Text = currentTime.Substring(currentTime.Length - 6, 1);
            lblT2.Text = currentTime.Substring(currentTime.Length - 7, 1);

            if (currentTime.Length == 7)
                lblT1.Text = String.Empty;
            else
                lblT1.Text = currentTime.Substring(currentTime.Length - 8, 1);
        }

        /// <summary>
        /// To Initialize all values
        /// </summary>
        private void InitializeValues()
        {
            logger.Info("On InitializeValues()");
            ShowTime();
            LoadBackGroundImage();

       //     imageButton_Click(imageDefaultButton);

            loadCaptureImage();
            loadMessageCombo1();
            loadCustomerNameCombo1();
            imageTextClear();
            setImageLabelTopPos();
            loadSystemFonts1();
            loadSystemFontColors1();
            isFormInitialized = true;
     //       imageButton_Click(imageDefaultButton);
        }

        /// <summary>
        /// To load the captured image in the Picture box
        /// </summary>
        private void loadCaptureImage()
        {
            logger.Info("On loadCaptureImage()");
            picboxImageCapture = new PictureBox();
            //picboxImageCapture.Location = new Point(0, 0);
            picboxImageCapture.Size = new Size(408, picboxOuter.Height);
            picboxImageCapture.CreateControl();
            picboxOuter.Controls.Add(picboxImageCapture);

            try
            {

                

                Bitmap tempImage = new Bitmap(Common.selectedPhotoPath());
                Bitmap img = new Bitmap(tempImage);
                tempImage.Dispose();
                picboxImageCapture.Image = (Image)img;
                picboxImageCapture.SizeMode = PictureBoxSizeMode.StretchImage;
                picboxImageCapture.Refresh();

            //    picboxImageBG = new PictureBox();
             //   picboxImageBG.Location = new Point(408, 0);
            ////    picboxImageBG.Size = new Size(345, picboxOuter.Height);
           //     picboxImageBG.CreateControl();


                ////
                
                //Bitmap tempImage2 = new Bitmap("C:\\Users\\Felix\\Documents\\mmtp\\MarqueeMoment\\MarqueeMoment\bin\x86\\Release\\Resources\\Background_Images\\1.jpeg");
                //Bitmap img2 = new Bitmap(tempImage2);
                //tempImage2.Dispose();
                //picboxImageBG.Image = (Image)img2;
                ////


                picboxOuter.Controls.Add(picboxImageBG);

              //  lblMessage = new Label();
                lblMessage = new ShadowLabel();
                lblMessage.BackColor = Color.Transparent;
                lblMessage.AutoSize = true;
                lblMessage.BorderStyle = System.Windows.Forms.BorderStyle.None;
             //   lblMessage.XOffset = 1;
            //    lblMessage.YOffset = 1;
                lblMessage.ForeColor = Color.White;
                lblMessage.ShadowColor = Color.Black;
                lblMessage.DrawGradient = false;
                lblMessage.CreateControl();
                picboxImageCapture.Controls.Add(lblMessage);

                lblCustomerName = new ShadowLabel();
                lblCustomerName.BackColor = Color.Transparent;
                lblCustomerName.AutoSize = true;
                lblCustomerName.BorderStyle = System.Windows.Forms.BorderStyle.None;
             //   lblCustomerName.XOffset = 1;
            //    lblCustomerName.YOffset = 1;
                lblCustomerName.ForeColor = Color.White;
                lblCustomerName.ShadowColor = Color.Black;
                lblCustomerName.DrawGradient = false;
                lblCustomerName.CreateControl();
                picboxImageCapture.Controls.Add(lblCustomerName);

                lblCustomerName2 = new ShadowLabel();
                lblCustomerName2.BackColor = Color.Transparent;
                lblCustomerName2.AutoSize = true;
                lblCustomerName2.BorderStyle = System.Windows.Forms.BorderStyle.None;
             //   lblCustomerName2.XOffset = 1;
            //    lblCustomerName2.YOffset = 1;
                lblCustomerName2.ForeColor = Color.White;
                lblCustomerName2.ShadowColor = Color.Black;
                lblCustomerName2.DrawGradient = false;
                lblCustomerName2.CreateControl();
                picboxImageCapture.Controls.Add(lblCustomerName2);

            }
            catch (Exception exc)
            {
                logger.Error(exc.StackTrace);
                MessageBox.Show("Error in loading captured Image");
            }

        }

        /// <summary>
        /// To fill the ComboBox with Greeting Messages
        /// </summary>
        private void loadMessageCombo()
        {
            logger.Info("On loadMessageCombo()");
            DataTable dtMessageName = null;
            if (bgWorker1.IsBusy != true)
            {
                bgWorker1.DoWork += new DoWorkEventHandler(bgWorker_DoWork_selectAllMessageNameWithAllowName);
                bgWorker1.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bgWorker_Completed_selectAllMessageNameWithAllowName);
                bgWorker1.RunWorkerAsync(dtMessageName);
            }
        }

        /// <summary>
        /// To fill the ComboBox with Greeting Messages
        /// </summary>
        private void loadMessageCombo1()
        {
            logger.Info("On loadMessageCombo1()");
            DataTable dtMessageName = MessageEntity.SelectAllMessageNameWithAllowName();
            if (dtMessageName != null)
            {
                comboGreetingMessage.DataSource = dtMessageName.DefaultView;
                comboGreetingMessage.DisplayMember = "MessageName";
                comboGreetingMessage.ValueMember = "AllowName";
                comboGreetingMessage.SelectedIndex = -1;
                comboGreetingMessage.Text = "Select a message";
            }

        }

        /// <summary>
        /// To fill the Combobox with Customer name
        /// </summary>
        private void loadCustomerNameCombo()
        {
            logger.Info("On loadCustomerNameCombo()");
            DataTable dtCustomerName1 = null;
            DataTable dtCustomerName2 = null;
            if (bgWorker2.IsBusy != true)
            {
                bgWorker2.DoWork += new DoWorkEventHandler(bgWorker_DoWork_loadCustomerNameCombo);
                bgWorker2.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bgWorker_Completed_loadCustomerNameCombo);
                bgWorker2.RunWorkerAsync(new DataTable[] { dtCustomerName1, dtCustomerName2 });
            }
        }

        /// <summary>
        /// To fill the Combobox with Customer name
        /// </summary>
        private void loadCustomerNameCombo1()
        {
            logger.Info("On loadCustomerNameCombo1()");
            DataTable dtCustomerName = CustomerEntity.SelectAllCustomerNameWithId();
            if (dtCustomerName != null)
            {
                for (Int32 count = 0; count < dtCustomerName.Rows.Count; count++)
                {
                    comboName.Items.Add(dtCustomerName.Rows[count][tblCustomer.CustomerName].ToString());
                    comboName2.Items.Add(dtCustomerName.Rows[count][tblCustomer.CustomerName].ToString());
                }
            }
        }

        /// <summary>
        /// To clear the text of the Image
        /// </summary>
        private void imageTextClear()
        {
            logger.Info("On imageTextClear()");
            lblMessage.Text = string.Empty;
            lblCustomerName.Text = string.Empty;
            lblCustomerName2.Text = string.Empty;
        }

        /// <summary>
        /// To set the position of the image on the screen
        /// </summary>
        private void setImageLabelLeftPos()
        {
            logger.Info("On setImageLabelLeftPos()");
            int messageWidth = lblMessage.Width;
            int customer1Width = lblCustomerName.Width;
            int customer2Width = lblCustomerName2.Width;
            int maxWidth = 0;

            if (messageWidth >= customer1Width && messageWidth >= customer2Width)
                maxWidth = messageWidth;
            else if (customer1Width >= customer2Width && customer1Width >= messageWidth)
                maxWidth = customer1Width;
            else
                maxWidth = customer2Width;

            lblMessage.Left = picboxImageCapture.Width - (maxWidth + 20);
            lblCustomerName.Left = lblMessage.Left;
            lblCustomerName2.Left = lblMessage.Left;
            logger.Info("On setImageLabelLeftPos() with LeftValue:" + lblMessage.Left.ToString());
        }

        /// <summary>
        /// use to set top position of image's label
        /// </summary>
        private void setImageLabelTopPos()
        {
            logger.Info("On setImageLabelTopPos()");
            int imageHeight = picboxImageCapture.Height;
            int messageHeight = lblMessage.Height;
            int customerHeight = lblCustomerName.Height;
            int customer2Height = lblCustomerName2.Height;

            int firstTop = imageHeight - (messageHeight + customerHeight + customer2Height + 7);
            int secondTop = firstTop + messageHeight + 2;
            int thirdTop = secondTop + customerHeight + 2;

            if (comboGreetingMessage.Text.Contains("[NAME1]") || comboGreetingMessage.Text.Contains("[NAME2]"))
            {
                lblMessage.Top = imageHeight - (messageHeight + 7);

                if ((!comboGreetingMessage.Text.Contains("[NAME1]") && comboName.Enabled) || (!comboGreetingMessage.Text.Contains("[NAME2]") && comboName2.Enabled))
                {
                    lblMessage.Top = lblMessage.Top - (customerHeight + 2);
                    lblCustomerName.Top = lblMessage.Top + messageHeight + 2;
                }

            }
            else if (String.IsNullOrEmpty(lblCustomerName2.Text))
            {
                if (String.IsNullOrEmpty(lblCustomerName.Text))
                    lblMessage.Top = thirdTop;
                else
                {
                    lblMessage.Top = secondTop;
                    lblCustomerName.Top = thirdTop;
                }
            }
            else if (String.IsNullOrEmpty(lblCustomerName.Text))
            {
                if (String.IsNullOrEmpty(lblCustomerName2.Text))
                    lblMessage.Top = thirdTop;
                else
                {
                    lblMessage.Top = secondTop;
                    lblCustomerName2.Top = thirdTop;
                }
            }
            else
            {
                lblMessage.Top = firstTop;
                lblCustomerName.Top = secondTop;
                lblCustomerName2.Top = thirdTop;
            }

            logger.Info("On setImageLabelTopPos(), lblMessage.Top:" + lblMessage.Top.ToString());
            logger.Info("On setImageLabelTopPos(), lblCustomerName.Top:" + lblCustomerName.Top.ToString());
            logger.Info("On setImageLabelTopPos(), lblCustomerName2.Top:" + lblCustomerName2.Top.ToString());
        
        }

        /// <summary>
        /// Use to set text on image's label
        /// </summary>
        private void setImageLabelText()
        {
            logger.Info("On setImageLabelText()");
            if (comboGreetingMessage.Text.Contains("[NAME1]") || comboGreetingMessage.Text.Contains("[NAME2]"))
            {
                String messageText = comboGreetingMessage.Text.Replace("[NAME1]", comboName.Text);
                messageText = messageText.Replace("[NAME2]", comboName2.Text);
                lblMessage.Text = messageText.Replace("\\n", "\n").Replace("Enter a second name", String.Empty).Replace("Enter a name", String.Empty);
                lblCustomerName.Text = String.Empty;
                lblCustomerName2.Text = String.Empty;

                if (!comboGreetingMessage.Text.Contains("[NAME1]") && comboName.Enabled && comboName.SelectedIndex >= 0)
                    lblCustomerName.Text = comboName.Text;
                else if (!comboGreetingMessage.Text.Contains("[NAME2]") && comboName2.Enabled && comboName2.SelectedIndex >= 0)
                    lblCustomerName.Text = comboName2.Text;
            }
            else
            {
                if (!comboGreetingMessage.Text.Contains("[NAME1]") && comboName.Enabled && comboName.SelectedIndex >= 0)
                    lblCustomerName.Text = (String.Equals(comboName.Text, "Enter a name") ? string.Empty : comboName.Text);
                if (!comboGreetingMessage.Text.Contains("[NAME2]") && comboName2.Enabled && comboName2.SelectedIndex >= 0)
                    lblCustomerName2.Text = (String.Equals(comboName2.Text, "Enter a second name") ? string.Empty : comboName2.Text);
            }

            logger.Info("On setImageLabelText(), lblMessage.Text:" + lblMessage.Text);
            logger.Info("On setImageLabelText(), lblCustomerName.Text:" + lblCustomerName.Text);
            logger.Info("On setImageLabelText(), lblCustomerName2.Text:" + lblCustomerName2.Text);
        }

        /// <summary>
        /// For loading the System fonts
        /// </summary>
        private void loadSystemFonts()
        {
            logger.Info("On loadSystemFonts()");
            ArrayList arrFonts = new ArrayList();
            if (bgWorker3.IsBusy != true)
            {
                bgWorker3.DoWork += new DoWorkEventHandler(bgWorker_DoWork_loadSystemFonts);
                bgWorker3.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bgWorker_Completed_loadSystemFonts);
                bgWorker3.RunWorkerAsync(arrFonts);
            }
        }

        /// <summary>
        /// For loading the System font colors
        /// </summary>
        private void loadSystemFontColors()
        {
            logger.Info("On loadSystemFontColors()");
            ArrayList arrFontColors = new ArrayList();
            if (bgWorker4.IsBusy != true)
            {
                bgWorker4.DoWork += new DoWorkEventHandler(bgWorker_DoWork_loadSystemFontColors);
                bgWorker4.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bgWorker_Completed_loadSystemFontColors);
                bgWorker4.RunWorkerAsync(arrFontColors);
            }
        }

        /// <summary>
        /// For loading the System fonts
        /// </summary>
        private void loadSystemFonts1()
        {
            logger.Info("On loadSystemFonts1()");
          //  foreach (System.Drawing.FontFamily f in System.Drawing.FontFamily.Families.Where(p => p.IsStyleAvailable(FontStyle.Regular)))
         //   {
          //      if (IsStyleSupported(f.Name, FontStyle.Regular))
            comboFontName.Items.Add("Polka MN");
            comboFontName.Items.Add("District Light");
            comboFontName.Items.Add("DynaGrotesk LXC Bold");

            comboFontName.SelectedIndex = 0;
           //         arrFonts.Add("Cooper");
          //          arrFonts.Add("Times New Roman");
            //        arrFonts.Add("Dominican");
           // }
        }

        /// <summary>
        /// For loading the System font colors
        /// </summary>
        private void loadSystemFontColors1()
        {
            logger.Info("On loadSystemFontColors1()");
         //   foreach (KnownColor knownColor in Enum.GetValues(typeof(KnownColor)))
        //    {
           //     Color color = Color.FromKnownColor(knownColor);
           //     if (!color.IsSystemColor)
           //     {
            comboFontColor.Items.Add("White");
            comboFontColor.Items.Add("Black");

            comboFontColor.SelectedIndex = 0;
            comboFontSize.SelectedIndex = 7;
            //    }
         //   }
        }

        /// <summary>
        /// For applying font property on image's label
        /// </summary>
        private void applyFonts()
        {
            logger.Info("On applyFonts()");
            float fontSize = 8;
            if (comboFontSize.SelectedIndex >= 0)
                fontSize = float.Parse(comboFontSize.SelectedItem.ToString());
            string fontName = "Polka MN";
            if (comboFontName.SelectedIndex >= 0)
                fontName = comboFontName.SelectedItem.ToString();

            lblMessage.Font = new System.Drawing.Font(fontName, fontSize, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            lblCustomerName.Font = new System.Drawing.Font(fontName, fontSize, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            lblCustomerName2.Font = new System.Drawing.Font(fontName, fontSize, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));

            setImageLabelLeftPos();
            setImageLabelTopPos();
        }

        /// <summary>
        /// For applying font color on image's label
        /// </summary>
        private void applyFontColor()
        {
            logger.Info("On applyFontColor()");
            Color newColor = System.Drawing.Color.White;
            Color newShadowColor = System.Drawing.Color.Black;
            if (comboFontColor.SelectedIndex >= 0)
                switch (comboFontColor.SelectedIndex)
                {
                    case 0:
                        newColor = Color.White;
                        newShadowColor = Color.Black;
                        break;
                    case 1:
                        newColor = Color.Black;
                        newShadowColor = Color.White;
                        break;
                    default:
                        newColor = Color.White;
                        newShadowColor = Color.Black;
                        break;
              //  newColor = (Color)comboFontColor.SelectedItem;
                }

            lblMessage.ForeColor = newColor;
            lblCustomerName.ForeColor = newColor;
            lblCustomerName2.ForeColor = newColor;
            lblMessage.ShadowColor = newShadowColor;
            lblCustomerName.ShadowColor = newShadowColor;
            lblCustomerName2.ShadowColor = newShadowColor;


        //    lblShadowText.ForeColor = newColor;
        }

        /// <summary>
        /// For releasing image from picture box
        /// </summary>
        private void releasePicBox()
        {
            logger.Info("On releasePicBox()");
            if (picboxOuter.Image != null)
                picboxOuter.Image.Dispose();

            if (picboxImageCapture.Image != null)
                picboxImageCapture.Image.Dispose();
        }

        /// <summary>
        /// To clear border of background button 
        /// </summary>
        private void ClearImageButtonBorder()
        {
            logger.Info("On ClearImageButtonBorder()");
            for (int count = 0; count < backgroundImageControll1.panelBG.Controls.Count; count++)
            {
                Button backgroundButton = backgroundImageControll1.panelBG.Controls[count] as Button;
                if (backgroundButton != null)
                    backgroundButton.FlatAppearance.BorderSize = 0;
            }
        }

        /// <summary>
        /// To load background image
        /// </summary>
        private void LoadBackGroundImage()
        {
            logger.Info("On LoadBackGroundImage()");
            Int32 yPOS = 4;
            Button imageDefaultButton = new Button(); //Default Background



            Bitmap imgBG = new Bitmap("C:\\Marquee-Moment\\Marquee_Moment\\bin\\Resources\\Background_Images\\0.jpg");
            picboxImageBG = new PictureBox();
            picboxImageBG.Location = new Point(408, 0);
            picboxImageBG.Size = new Size(345, picboxOuter.Height);
            picboxImageBG.CreateControl();


            picboxImageBG.Image = (Image)imgBG;
            picboxImageBG.SizeMode = PictureBoxSizeMode.Normal;
            backgroundSelected = true;


            for (int count = 0; count < 10; count++)
            {
                String bgImagePath = Common.composeBGImageListDirPath + (count + 1).ToString() + ".jpg";

                logger.Info("On LoadBackGroundImage(), bgImagePath:" + bgImagePath);
                 
                Button imageButton = new Button();
                Bitmap tempImage = new Bitmap(bgImagePath);

                Bitmap img = new Bitmap(tempImage);

                tempImage.Dispose();

                imageButton.BackgroundImage = (Image)img;

                imageButton.BackgroundImageLayout = ImageLayout.Stretch;
                imageButton.Size = new System.Drawing.Size(150, 40);
                imageButton.FlatAppearance.BorderSize = 0;
                imageButton.FlatAppearance.BorderColor = Color.PaleGreen;
                imageButton.FlatStyle = FlatStyle.Flat;
                imageButton.Cursor = System.Windows.Forms.Cursors.Hand;
                imageButton.Location = new System.Drawing.Point(4, yPOS);
                imageButton.Tag = count;
                imageButton.Click += new System.EventHandler(this.imageButton_Click);
                    
                if (count == 0)
                    picboxImageBG.Image = (Image)img;
    
                backgroundImageControll1.panelBG.Controls.Add(imageButton);

                yPOS = yPOS + imageButton.Height + 10;
            }
        }


        /// <summary>
        /// To Combine Images
        /// </summary>
        /// <param name="imageList">bitmap list</param>
        /// <returns>Final Image file</returns>
        public static System.Drawing.Bitmap Combine(List<System.Drawing.Bitmap> imageList)
        {
            logger.Info("On Combine(List<System.Drawing.Bitmap> imageList)");
            if (imageList.Count == 0)
                return null;

            //read all images into memory
            List<System.Drawing.Bitmap> images = new List<System.Drawing.Bitmap>();
            System.Drawing.Bitmap finalImage = null;

            try
            {
                int width = 0;
                int height = 0;

                foreach (Bitmap image in imageList)
                {
                    //create a Bitmap from the file and add it to the list
                    System.Drawing.Bitmap bitmap = image;

                    //update the size of the final bitmap
                    width += bitmap.Width;
                    height = bitmap.Height > height ? bitmap.Height : height;

                    images.Add(bitmap);
                }


                //create a bitmap to hold the combined image
                finalImage = new System.Drawing.Bitmap(width, height, images[1].PixelFormat);

                //get a graphics object from the image so we can draw on it
                using (System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(finalImage))
                {
                    //set background color
                    g.Clear(System.Drawing.Color.Black);
                    g.CompositingQuality = CompositingQuality.HighQuality;

                    //go through each image and draw it on the final image
                    int offset = 0;
                    foreach (System.Drawing.Bitmap image in images)
                    {

                        g.DrawImage(image,
                          new System.Drawing.Rectangle(offset, 0, image.Width, image.Height));
                        offset += image.Width;
                    }
                }

                if (finalImage != null)
                    logger.Info("On Combine(),resulted finalImage Width:" + finalImage.Width.ToString() + " Height:" + finalImage.Height.ToString());

                return finalImage;
            }
            catch (Exception ex)
            {
                if (finalImage != null)
                    finalImage.Dispose();

                throw ex;
            }
            finally
            {
                //clean up memory
                foreach (System.Drawing.Bitmap image in images)
                {
                    image.Dispose();
                }
            }
        }

        /// <summary>
        /// Merges Images into 1 Image.
        /// </summary>
        /// <param name="images">The Images you want merge</param>
        /// <returns>An Image of all images</returns>
        public static Image MergeImages(Image[] images)
        {
            logger.Info("On MergeImages(Image[] images)");
            if (images == null || images.Length <= 0)
            {
                return null;
            }
            Int32 imageWSize = 0;
            Int32 imageHSize = 0;

            for (int i = 0; i < images.Length; i++)
            {
                imageWSize += images[i].Width;

                if (images[i].Height > imageHSize)
                    imageHSize = images[i].Height;
            }

            Int32 width = 0;
            Int32 height = 0;
            int picsInOneLine = 10;

            if (images.Length >= picsInOneLine)
            {
                width = picsInOneLine * imageWSize;
                decimal d = (images.Length + picsInOneLine) / picsInOneLine;
                height = (int)Math.Round(d) * imageHSize;
            }
            else
            {
                width = imageWSize;
                height = imageHSize;
            }

            Bitmap bitmap = new Bitmap(width, height);
            int hhh = -1;
            int www = 0;
            for (int i = 0; i < images.Length; i++)
            {
                Bitmap image = new Bitmap(images[i]);
                if (i % picsInOneLine == 0)
                {
                    hhh++;
                    www = 0;
                }

                imageWSize = image.Width;
                imageHSize = image.Height;


                //Get All of the x Pixels
                for (int w = 0; w < imageWSize; w++)
                {
                    //Get All of the Y Pixels
                    for (int h = 0; h < imageHSize; h++)
                    {
                        //Set the Cooresponding Pixel
                        int ww = w + (www * 408);//408<--345

                        int hh = h + (hhh * imageHSize);
                        bitmap.SetPixel(ww, hh, image.GetPixel(w, h));
                    }
                }
                www++;

            }
            //Return the new Bitmap
            return bitmap;
        }


        #endregion For User Define Method

        #region for System Events

        private void imageButton_Click(object sender, EventArgs e)
        {
            logger.Info("On imageButton_Click(object sender, EventArgs e)");
            ClearImageButtonBorder();
            Button imageButton = sender as Button;
            imageButton.FlatAppearance.BorderSize = 2;

            backgroundSelected = true;
            selectedBGImageIndex = (int)imageButton.Tag;
            logger.Info("On imageButton_Click(), selectedBGImageIndex:" + selectedBGImageIndex.ToString());
            String bgImagePath = Common.composeBGImageListDirPath + (selectedBGImageIndex + 1).ToString() + ".jpg";
            logger.Info("On imageButton_Click(),bgImagePath:" + bgImagePath);
            if (File.Exists(bgImagePath))
            {
                logger.Info("On imageButton_Click(),File exist:True");
                Bitmap tempImage = new Bitmap(bgImagePath);
                Bitmap img = new Bitmap(tempImage);
                tempImage.Dispose();
                picboxImageBG.Image = (Image)img;
            }
            picboxImageBG.SizeMode = PictureBoxSizeMode.Normal;
            picboxImageBG.Refresh();
        }

        private void btnMenu_Click(object sender, EventArgs e)
        {
            logger.Info("On btnMenu_Click(object sender, EventArgs e)");
            frmDialog customBox = new frmDialog("Warning", "All of your changes will be lost, do you wish to continue?");
            if (customBox.ShowDialog() == System.Windows.Forms.DialogResult.Yes)
            {
                this.Close();
            }
        }

        private void btnSubmit_Click(object sender, EventArgs e)
        {
            logger.Info("On btnSubmit_Click(object sender, EventArgs e)");
            if (!backgroundSelected)
            {
                picboxOuter.Focus();
                Dialogs.Information("Please select background");
                return;
            }
            try
            {
                Image RightImage;
                Graphics g1 = picboxImageCapture.CreateGraphics();
                Image leftImage = new Bitmap(picboxImageCapture.ClientRectangle.Width, picboxImageCapture.ClientRectangle.Height, g1);
                Graphics g2 = Graphics.FromImage(leftImage);
                IntPtr dc1 = g1.GetHdc();
                IntPtr dc2 = g2.GetHdc();
                BitBlt(dc2, 0, 0, picboxImageCapture.ClientRectangle.Width, picboxImageCapture.ClientRectangle.Height, dc1, 0, 0, 13369376);
                g1.ReleaseHdc(dc1);
                g2.ReleaseHdc(dc2);

                String bgImagePath = Common.composeBGImageListDirPath + (selectedBGImageIndex + 1).ToString() + ".jpg";
                logger.Info("On btnSubmit_Click(), bgImagePath:" + bgImagePath);
                if (File.Exists(bgImagePath))
                {
                    logger.Info("On btnSubmit_Click(), FileExist:True");
                    Bitmap tempImage = new Bitmap(bgImagePath);
                    Bitmap img = new Bitmap(tempImage);
                    tempImage.Dispose();
                    RightImage = (Image)img;

                    if (RightImage!=null && leftImage!=null)
                        logger.Info("Adding two images having LeftImage width:" + leftImage.Width.ToString() + " Height:" + leftImage.Height.ToString() + " and RightImage width:" + RightImage.Width.ToString() + " Height:" + RightImage.Height.ToString());
                    
                    List<System.Drawing.Bitmap> images = new List<Bitmap>();
                    images.Add((Bitmap)leftImage);
                    images.Add((Bitmap)RightImage);

                    //combine them into one image
                    System.Drawing.Bitmap bitmap = Combine(images);
                    if (bitmap == null)
                    {
                        logger.Info("Error at saving composed image due to null bitmap result on bitmap = Combine(images");
                        Dialogs.Error("Error at saving composed image");
                        return;
                    }

                    try
                    {
                        if (!Directory.Exists(Common.composedPhotoDirPath))
                            Directory.CreateDirectory(Common.composedPhotoDirPath);
                        logger.Info("On btnSubmit_Click(), bitmap.Save(Common.composedPhotoPath(), ImageFormat.Png) , Common.composedPhotoPath():" + Common.composedPhotoPath());
                        bitmap.Save(Common.composedPhotoPath(), ImageFormat.Png);
                        bitmap.Dispose();
                    }
                    catch (Exception exc)
                    {
                        logger.Error(exc.StackTrace);
                        Dialogs.Error("Error at saving composed image");
                    }

                    this.Visible = false;
                    frmScheduleScreen obSchedule = new frmScheduleScreen();
                    obSchedule.ShowDialog();
                    this.Close();
                }
            }
            catch (Exception exc)
            {
                logger.Error(exc.StackTrace);
                Dialogs.Error("Error on saving composition changes");
            }

        }

        private void comboGreetingMessage_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (isFormInitialized)
            {
                logger.Info("On comboGreetingMessage_SelectedIndexChanged(object sender, EventArgs e), comboGreetingMessage.SelectedIndex:" + comboGreetingMessage.SelectedIndex.ToString());
                if (comboGreetingMessage.SelectedIndex >= 0)
                {
                    comboGreetingMessage_Validating(null, null);
                    lblMessage.Text = comboGreetingMessage.Text.Replace("\\n", "\n");
                    setImageLabelText();
                    setImageLabelLeftPos();
                    setImageLabelTopPos();
                }
                else
                    lblMessage.Text = string.Empty;
            }
        }

        private void comboGreetingMessage_Validating(object sender, CancelEventArgs e)
        {
            logger.Info("On comboGreetingMessage_Validating(object sender, CancelEventArgs e)");
            if (comboGreetingMessage.SelectedIndex >= 0 && comboGreetingMessage.SelectedValue.ToString() != "System.Data.DataRowView")
            {
                Int32 allowName = int.Parse(comboGreetingMessage.SelectedValue.ToString());
                logger.Info("On comboGreetingMessage_Validating() with allowName:" + allowName.ToString());
                switch (allowName)
                {
                    case 0:
                        lblCustomerName.Text = string.Empty;
                        lblCustomerName2.Text = string.Empty;
                        comboName.Text = "Enter a name";
                        comboName2.Text = "Enter a second name";
                        comboName.Enabled = false;
                        comboName2.Enabled = false;
                        break;
                    case 1:
                        lblCustomerName2.Text = string.Empty;
                        comboName2.Text = "Enter a second name";
                        comboName.Enabled = true;
                        comboName2.Enabled = false;
                        break;
                    case 2:
                        comboName.Enabled = true;
                        comboName2.Enabled = true;
                        break;
                    default:
                        break;

                }
            }
            else if (!String.Equals(comboGreetingMessage.Text, "Select a message") && !String.IsNullOrEmpty(comboGreetingMessage.Text) && comboGreetingMessage.Items.Count > 0 && comboGreetingMessage.SelectedIndex == -1)
                comboGreetingMessage.SelectedIndex = 0;
            else if (String.Equals(comboGreetingMessage.Text.Trim(), String.Empty) || String.Equals(comboGreetingMessage.Text.Trim(), "Select a message"))
                lblMessage.Text = string.Empty;

            setImageLabelText();
            setImageLabelLeftPos();
            setImageLabelTopPos();
        }

        private void comboName_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (isFormInitialized)
            {
                logger.Info("On comboName_SelectedIndexChanged(object sender, EventArgs e) comboName.SelectedIndex:" + comboName.SelectedIndex.ToString());
                if (comboName.SelectedIndex >= 0)
                {
                    setImageLabelText();
                    setImageLabelLeftPos();
                    setImageLabelTopPos();
                }
            }
        }

        private void comboName2_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (isFormInitialized)
            {
                logger.Info("On comboName2_SelectedIndexChanged(object sender, EventArgs e) comboName2.SelectedIndex:" + comboName2.SelectedIndex.ToString());
                if (comboName2.SelectedIndex >= 0)
                {
                    setImageLabelText();
                    setImageLabelLeftPos();
                    setImageLabelTopPos();
                }
            }
        }

        private void comboName_Validating(object sender, CancelEventArgs e)
        {
            logger.Info("On comboName_Validating(object sender, CancelEventArgs e)");
            if (!String.IsNullOrEmpty(comboName.Text) && !String.Equals(comboName.Text,"Enter a name") && comboName.Items.Count > 0 && comboName.SelectedIndex == -1)
                comboName.SelectedIndex = 0;

            setImageLabelText();
            if (comboName.Text == string.Empty)
                lblCustomerName.Text = string.Empty;


            setImageLabelLeftPos();
            setImageLabelTopPos();
        }

        private void comboName2_Validating(object sender, CancelEventArgs e)
        {
            logger.Info("On comboName2_Validating(object sender, CancelEventArgs e)");
            if (!String.IsNullOrEmpty(comboName2.Text) && !String.Equals(comboName2.Text, "Enter a second name") && comboName2.Items.Count > 0 && comboName2.SelectedIndex == -1)
                comboName2.SelectedIndex = 0;

            setImageLabelText();
            if (comboName2.Text == string.Empty)
                lblCustomerName2.Text = string.Empty;

            setImageLabelLeftPos();
            setImageLabelTopPos();
        }

        private void comboFontSize_SelectedIndexChanged(object sender, EventArgs e)
        {
            logger.Info("On comboFontSize_SelectedIndexChanged(object sender, EventArgs e) comboFontSize.SelectedIndex:" + comboFontSize.SelectedIndex.ToString());
            if (comboFontSize.SelectedIndex >= 0)
                applyFonts();
        }

        private void comboFontName_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (isFormInitialized)
            {
                logger.Info("On comboFontName_SelectedIndexChanged(object sender, EventArgs e) comboFontName.SelectedIndex:" + comboFontName.SelectedIndex.ToString());
                if (comboFontName.SelectedIndex >= 0)
                    applyFonts();
            }
        }

        private void comboFontColor_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (isFormInitialized)
            {
                logger.Info("On comboFontColor_SelectedIndexChanged(object sender, EventArgs e) comboFontColor.SelectedIndex:" + comboFontColor.SelectedIndex.ToString());
                if (comboFontColor.SelectedIndex >= 0)
                    applyFontColor();
            }
        }

        private void comboFontName_Validating(object sender, CancelEventArgs e)
        {
            logger.Info("On comboFontName_Validating(object sender, CancelEventArgs e)");
            if (!String.IsNullOrEmpty(comboFontName.Text) && !String.Equals(comboFontName.Text, "Select a font") && comboFontName.Items.Count > 0 && comboFontName.SelectedIndex == -1)
                comboFontName.SelectedIndex = 0;

        }

        private void comboFontColor_Validating(object sender, CancelEventArgs e)
        {
            logger.Info("On comboFontColor_Validating(object sender, CancelEventArgs e)");
            if (!String.IsNullOrEmpty(comboFontColor.Text) && !String.Equals(comboFontColor.Text, "Select a font color") && comboFontColor.Items.Count > 0 && comboFontColor.SelectedIndex == -1)
                comboFontColor.SelectedIndex = 0;

        }

        private void comboFontSize_Validating(object sender, CancelEventArgs e)
        {
            logger.Info("On comboFontSize_Validating(object sender, CancelEventArgs e)");
            if (!String.IsNullOrEmpty(comboFontSize.Text) && !String.Equals(comboFontSize.Text, "Select a font size") && comboFontSize.Items.Count > 0 && comboFontSize.SelectedIndex == -1)
                comboFontSize.SelectedIndex = 0;

        }

        private void frmComposeMessage_FormClosing(object sender, FormClosingEventArgs e)
        {
            logger.Info("On frmComposeMessage_FormClosing(object sender, FormClosingEventArgs e) with formClose:" + formClose.ToString());
            if (!formClose)
            {
                this.Visible = true;
                e.Cancel = true;
                formClose = true;
                return;
            }
            releasePicBox();
        }

        private void btnBackToPhoto_Click(object sender, EventArgs e)
        {
            logger.Info("On btnBackToPhoto_Click(object sender, EventArgs e), _imageFromCamera:" + _imageFromCamera.ToString());
            picboxOuter.Focus();
            frmDialog customBox = new frmDialog("Warning", "All of your changes will be lost, do you wish to continue?");
            if (customBox.ShowDialog() == System.Windows.Forms.DialogResult.Yes)
            {
                if (!_imageFromCamera)
                {
                    this.Close();
                    return;
                }

                try
                {
                    this.Visible = false;
                    frmReviewPhotos objReview = new frmReviewPhotos();
                    objReview.ShowDialog();
                    this.Close();
                }
                catch (Exception exc)
                {
                    logger.Error(exc.StackTrace);
                    MessageBox.Show(exc.StackTrace);
                }

            }
        }

        private void timerCompose_Tick(object sender, EventArgs e)
        {
            ShowTime();
        }


        #endregion for System Events

        #region BackgroundWorker

        private void bgWorker_DoWork_selectAllMessageNameWithAllowName(object sender, DoWorkEventArgs e)
        {
            logger.Info("On bgWorker_DoWork_selectAllMessageNameWithAllowName(object sender, DoWorkEventArgs e)");
            DataTable dtMessageName = e.Argument as DataTable;
            dtMessageName = MessageEntity.SelectAllMessageNameWithAllowName();
            e.Result = dtMessageName;
        }

        private void bgWorker_Completed_selectAllMessageNameWithAllowName(object sender, RunWorkerCompletedEventArgs e)
        {
            logger.Info("On bgWorker_Completed_selectAllMessageNameWithAllowName(object sender, RunWorkerCompletedEventArgs e)");
            comboGreetingMessage.DataSource = e.Result as DataTable;
            comboGreetingMessage.DisplayMember = "MessageName";
            if (comboGreetingMessage.DataSource != null)
            {
                comboGreetingMessage.ValueMember = "AllowName";
                comboGreetingMessage.SelectedIndex = -1;
                comboGreetingMessage.Text = "Select a message";
            }

            bgWorker1.DoWork -= bgWorker_DoWork_selectAllMessageNameWithAllowName;
            bgWorker1.RunWorkerCompleted -= bgWorker_Completed_selectAllMessageNameWithAllowName;


        }

        private void bgWorker_DoWork_loadCustomerNameCombo(object sender, DoWorkEventArgs e)
        {
            logger.Info("On bgWorker_DoWork_loadCustomerNameCombo(object sender, DoWorkEventArgs e)");
            DataTable[] dtCustomer = e.Argument as DataTable[];
            dtCustomer[0] = CustomerEntity.SelectAllCustomerNameWithId();
            dtCustomer[1] = CustomerEntity.SelectAllCustomerNameWithId();
            e.Result = dtCustomer;

        }

        private void bgWorker_Completed_loadCustomerNameCombo(object sender, RunWorkerCompletedEventArgs e)
        {
            logger.Info("On bgWorker_Completed_loadCustomerNameCombo(object sender, RunWorkerCompletedEventArgs e)");
            DataTable[] dtCustomer = e.Result as DataTable[];
            DataTable dtCustomerName1 = dtCustomer[0];
            DataTable dtCustomerName2 = dtCustomer[1];
            comboName.DataSource = dtCustomerName1;
            comboName.DisplayMember = "CustomerName";
            comboName2.DataSource = dtCustomerName2;
            comboName2.DisplayMember = "CustomerName";
            if (comboName.DataSource != null)
            {
                comboName.ValueMember = "CustomerId";
                comboName2.ValueMember = "CustomerId";
                comboName.SelectedIndex = -1;
                comboName2.SelectedIndex = -1;
                comboName.Text = "Enter a name";
                comboName2.Text = "Enter a second name";
            }
            bgWorker2.DoWork -= bgWorker_DoWork_loadCustomerNameCombo;
            bgWorker2.RunWorkerCompleted -= bgWorker_Completed_loadCustomerNameCombo;
        }

        private void bgWorker_DoWork_loadSystemFonts(object sender, DoWorkEventArgs e)
        {
            logger.Info("On bgWorker_DoWork_loadSystemFonts(object sender, DoWorkEventArgs e)");
         //   ArrayList arrFonts = e.Argument as ArrayList;
            ArrayList arrFonts = new ArrayList();
            arrFonts.Add("District Light");
            arrFonts.Add("Polka MN");
            arrFonts.Add("DynaGrotesk LXC Bold");
            //foreach (System.Drawing.FontFamily f in System.Drawing.FontFamily.Families.Where(p => p.IsStyleAvailable(FontStyle.Regular)))
            //{
            //    if (IsStyleSupported(f.Name, FontStyle.Regular))
            //        arrFonts.Add(f.Name);
            //}

            e.Result = arrFonts;
        }

        private Boolean IsStyleSupported(String familyName, System.Drawing.FontStyle style)
        {
            logger.Info("On IsStyleSupported(String familyName, System.Drawing.FontStyle style) with FontStyle:Regular, familyName:" + familyName);

            Boolean result = false;
            try
            {
                Font f = new Font(familyName, 8, style);
                f.Dispose();
                result = true;
                logger.Info("On IsStyleSupported() Return:True");
            }
            catch (System.ArgumentException exc)
            {
                logger.Error(exc.StackTrace);
                logger.Info("On IsStyleSupported() Return:False -NOT SUPPORTED");
            }

            return result;
        }

        private void bgWorker_Completed_loadSystemFonts(object sender, RunWorkerCompletedEventArgs e)
        {
          //  logger.Info("On bgWorker_Completed_loadSystemFonts(object sender, RunWorkerCompletedEventArgs e)");
          //  ArrayList list = e.Result as ArrayList;
            ArrayList list = new ArrayList();
            list.Add("Polka MN");
            list.Add("District Light");
            list.Add("DynaGrotesk LXC Bold");
            comboFontName.DataSource = list;
            if (comboFontName.DataSource != null)
            {
                comboFontName.SelectedIndex = -1;
                comboFontName.Text = "Select a font";
            }

           // bgWorker3.DoWork -= bgWorker_DoWork_loadSystemFonts;
           // bgWorker3.RunWorkerCompleted -= bgWorker_Completed_loadSystemFonts;
        }
        private void bgWorker_DoWork_loadSystemFontColors(object sender, DoWorkEventArgs e)
        {
            logger.Info("On bgWorker_DoWork_loadSystemFontColors(object sender, DoWorkEventArgs e)");
        //    ArrayList arrFontColor = e.Argument as ArrayList;
            ArrayList list = new ArrayList();
            list.Add("White");
            list.Add("Black");
            comboFontName.DataSource = list;
            if (comboFontName.DataSource != null)
            {
                comboFontName.SelectedIndex = -1;
                comboFontName.Text = "Select a font";
            }
        }

        private void bgWorker_Completed_loadSystemFontColors(object sender, RunWorkerCompletedEventArgs e)
        {
            logger.Info("On bgWorker_Completed_loadSystemFontColors(object sender, RunWorkerCompletedEventArgs e)");
        //    ArrayList list = e.Result as ArrayList;
            ArrayList list = new ArrayList();
            list.Add("White");
            list.Add("Black");
            comboFontColor.DataSource = list;

            if (comboFontColor.DataSource != null)
            {
                comboFontColor.SelectedIndex = -1;
                comboFontColor.Text = "Select a font color";
            }

         //   bgWorker4.DoWork -= bgWorker_DoWork_loadSystemFontColors;
         //   bgWorker4.RunWorkerCompleted -= bgWorker_Completed_loadSystemFontColors;
        }

        #endregion BackgroundWorker

    }
}
